package com.huawei.petapp2.cart;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huawei.petapp2.R;
import com.huawei.petapp2.call.ShoppingcartBeanCallback;
import com.huawei.petapp2.constant.HttpUrl;
import com.huawei.petapp2.entity.Result;
import com.huawei.petapp2.entity.Shoppingcart;
import com.huawei.petapp2.utils.DateUtil;
import com.huawei.petapp2.utils.PreferenceHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CartListAdapter extends BaseAdapter {

    private Context mContext;
    private List<Shoppingcart> cartGoods;
    private Shoppingcart itemcart;
    private CartDBOpenHelper dbOpenHelper;
    private List<Shoppingcart> shoppingcart;
    private View mView;
    final private static Gson gson=new GsonBuilder().serializeNulls().create();

    public CartListAdapter(Context mContext, List<Shoppingcart> cartGoods) {
        this.mContext = mContext;
        this.cartGoods = cartGoods;
    }

    @Override
    public int getCount() {
        return cartGoods.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    static class ViewHolder {
        ImageView cart_photo;
        TextView cart_name;
        TextView cart_type;
        TextView cart_price;
        TextView cart_num;
        ImageView cart_jian, cart_jia;
        CheckBox cart_check;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        this.mView=convertView;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.cart_item, parent, false);
            holder = new ViewHolder();
            holder.cart_photo = convertView.findViewById(R.id.cart_photo);
            holder.cart_name = convertView.findViewById(R.id.cart_name);
            holder.cart_type = convertView.findViewById(R.id.cart_type);
            holder.cart_price = convertView.findViewById(R.id.cart_price);
            holder.cart_num = convertView.findViewById(R.id.cart_num);
            holder.cart_jian = convertView.findViewById(R.id.cart_jian);
            holder.cart_jia = convertView.findViewById(R.id.cart_jia);
            holder.cart_check = convertView.findViewById(R.id.cart_check);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if(mContext!=null)
            Glide.with(mContext)
                    .load(cartGoods.get(position).getProductImg())
                    .into(holder.cart_photo);
       // holder.cart_photo.setBackgroundResource(cartGoods.get(position).getProductImg());
        holder.cart_name.setText(cartGoods.get(position).getProductName());
        holder.cart_type.setText(cartGoods.get(position).getSkuName());
        holder.cart_price.setText(String.valueOf(cartGoods.get(position).getOriginalPrice()));
        holder.cart_num.setText(String.valueOf(cartGoods.get(position).getCartNum()));
        if((cartGoods.get(position).getIsselect()==1)){
            holder.cart_check.setChecked(true);
        }

        holder.cart_jia.setOnClickListener(v -> {
            int g_id = cartGoods.get(position).getCartId();
            getShoppingcart(this.mView,g_id);
        });

        holder.cart_jian.setOnClickListener(v -> {
            int g_id = cartGoods.get(position).getCartId();
            String token=PreferenceHelper.getString("token",Objects.requireNonNull(mContext));
            OkHttpClient client = new OkHttpClient();
            Request request1 = new Request.Builder()//获取改用户全部地址
                    .url(HttpUrl.getBaseUrl()+"/shopcart/listbycids/"+g_id)
                    .addHeader("Token",token)
                    .build();

            client.newCall(request1).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code() >= 200 && response.code() < 300) {
                        String results = response.body().string();
                        Result result=gson.fromJson(results,Result.class);
                        System.out.println("新的获取购物车数据OnintView"+result);
                        itemcart= DateUtil.getEntity(result, Shoppingcart.class);
                        int num =Integer.parseInt(itemcart.getCartNum());
                        if (num == 1){
                            // delCartGoods(g_id);
                            //notifyDataSetChanged();
                            Toast.makeText(mContext, "最后一个了，不能再减了~", Toast.LENGTH_SHORT).show();
                        }else {
                            holder.cart_num.setText(String.valueOf(num - 1));
                            uptGoodsNum(g_id,num - 1);
                        }
                    }
                }
            });


        });

        holder.cart_check.setOnCheckedChangeListener((buttonView, isChecked) -> {
            int g_id = cartGoods.get(position).getCartId();
            if (holder.cart_check.isChecked()){
                uptGoodsChecked(g_id,"true");
                Toast.makeText(mContext, "改为true", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(mContext, "改为false", Toast.LENGTH_SHORT).show();
                uptGoodsChecked(g_id,"false");
            }
        });

        return convertView;
    }

    public List<Shoppingcart> getShoppingcart(View view,int g_id)
    {
        ViewHolder holder;
        holder = new ViewHolder();
        int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(mContext));
        String token=PreferenceHelper.getString("token",Objects.requireNonNull(mContext));
        Shoppingcart shoppingcarts;
        Map<String, String> params = new HashMap<String, String>();
        params.put("name", "zhy");
        String url = HttpUrl.getBaseUrl()+"/shopcart/listbycids/"+g_id;
        OkHttpUtils//
                .get()//
                .url(url)//
//                .params(params)//
                .addHeader("Token",token)
                .build()//
                .execute(new ShoppingcartBeanCallback()//
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {

                    }

                    @Override
                    public void onResponse(Shoppingcart response, int id)
                    {
                        itemcart=response;
                        int num =Integer.parseInt(itemcart.getCartNum());
                        holder.cart_num = view.findViewById(R.id.cart_num);
                        System.out.println("当前的购物车数目"+num);
                        holder.cart_num.setText(String.valueOf(num + 1));
                        uptGoodsNum(g_id,num + 1);
                        System.out.println("相应的数据"+response);
                    }
                });
        return shoppingcart;

    }

    public void updateCartNum(int g_id,int g_num,View mView)
    {
        this.mView=mView;
        int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(mContext));
        String token=PreferenceHelper.getString("token",Objects.requireNonNull(mContext));
        Shoppingcart shoppingcarts;
        Map<String, String> params = new HashMap<String, String>();
        params.put("name", "zhy");
        String url = HttpUrl.getBaseUrl()+"/shopcart/updateNum/"+g_id+"/"+g_num;
        OkHttpUtils//
                .get()//
                .url(url)//
//                .params(params)//
                .addHeader("Token",token)
                .build()//
                .execute(new StringCallback()//
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ViewHolder holder;
                        holder = new ViewHolder();
                        holder.cart_num = mView.findViewById(R.id.cart_num);
                        holder.cart_num.setText(String.valueOf(g_num));
                        System.out.println("更新商品数量成功"+response);
                    }

                });
    }


    //存在返回商品数量
    private int getGoodsNum(int g_id) {
        dbOpenHelper = new CartDBOpenHelper(mContext, 1);
        //表名，列名，where约束条件，where中占位符提供具体的值，指定group by的列，进一步约束
        Cursor cursor = dbOpenHelper.getReadableDatabase().query(
                "cart",
                new String[]{"g_num"},
                "g_id=?",
                new String[]{String.valueOf(g_id)},
                null,
                null,
                null);
        cursor.moveToFirst();

        String str = cursor.getString(0);
        cursor.close();
        dbOpenHelper.close();
        return Integer.parseInt(str);
    }

    //修改商品数量
    private void uptGoodsNum(int g_id, int g_num) {
        updateCartNum(g_id,g_num,this.mView);
        /*String token=PreferenceHelper.getString("token",Objects.requireNonNull(mContext));

        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()//获取改用户全部地址
                .url(HttpUrl.getBaseUrl()+"/shopcart/updateNum/"+g_id+"/"+g_num)
                .addHeader("Token",token)
                .build();
        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String results = response.body().string();
                    Result result=gson.fromJson(results,Result.class);
                    System.out.println("获取新的购物车数据"+result);
                    //刷新当前activity
                }
            }
        });*/
    }

    //修改商品是否被选中
    private void uptGoodsChecked(int g_id, String isChecked){
        int isselect=0;
        int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(mContext));
        String token=PreferenceHelper.getString("token",Objects.requireNonNull(mContext));
        if(isChecked.equals("true"))
        {
            isselect=1;
        }
        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()//获取改用户全部地址
                .url(HttpUrl.getBaseUrl()+"/shopcart/updateSelect/"+g_id+"/"+isselect)
                .addHeader("Token",token)
                .build();
        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String results = response.body().string();
                    Result result=gson.fromJson(results,Result.class);
                    System.out.println("新的获取订单请求请求"+result);
                    //刷新当前activity
                }
            }
        });
    }
}
